//
//  DDAppDelegate.m
//  PrivateCloud
//
//  Created by ;; doo on 13-9-26.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDAppDelegate.h"
#import "ListViewController.h"
#import "FileOperation.h"
#import "DDLoginViewController.h"
#import "DDAddressBookUtils.h"
#import "TestAddressBook.h"
#import "DDContactInfosView.h"
#import "DDVerifyThread.h"
#import "DDTCPListenThread.h"
#include <AssetsLibrary/AssetsLibrary.h>
#import "DDImagePickerController.h"
#import "FileOperation.h"
#import "DDConstants.h"
#import "DDAddressBookUtils.h"
#include <AVFoundation/AVFoundation.h>
@implementation DDAppDelegate


@synthesize loginViewController = _loginViewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //MARS UI 目前默认显示数据密码的界面，然后点击确定按钮连接
    self.loginViewController = [[[DDLoginViewController alloc] initWithNibName:nil bundle:nil] autorelease];
    self.window.rootViewController = self.loginViewController;
    //创建默认的文件夹
    FileOperation* fileOp = [[FileOperation alloc]init];
    [fileOp createDirectory];
    NSArray* allLocalFolderInfos = [fileOp searchAllFiles:^{
//        [DDConstants shardLocalFolderInfos];
//        NSArray* arr = [[[DDConstants shardLocalFolderInfos]objectAtIndex:0]files];
//        DDImagePickerController *imageC = [[DDImagePickerController alloc]initWithNibName:nil bundle:nil];
//        imageC.fileDataSource = arr;
//        self.window.rootViewController = imageC;
    }];
    ABAddressBookRef addressBook = ABAddressBookCreate();
    
    //FIX ME 通讯录权限
   /* __block BOOL accessGranted = NO;
    if (ABAddressBookRequestAccessWithCompletion != NULL) {
        
        // we're on iOS 6
        NSLog(@"on iOS 6 or later, trying to grant access permission");
        
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(sema);
        });
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else { // we're on iOS 5 or older
        
        NSLog(@"on iOS 5 or older, it is OK");
        accessGranted = YES;
    }
    
    if (accessGranted) {
        
        NSLog(@"we got the access right");
    }*/
    
    DDAddressBookUtils *bookUtils = [[DDAddressBookUtils alloc]init];
    NSString* bookPath = [bookUtils getRemoteVcfPath];
    if(bookPath == nil){
        [bookUtils createVcfFileWithCode:SERVER_CODE];
    }
    
 //   NSString* vPath = @"/Users/mars/Library/Application Support/iPhone Simulator/7.0/Applications/5100B004-D9DB-46D5-877F-0CACA7F72699/tmp/aaa.mp4";
    NSString* vPath = @"/Users/mars/Library/Application Support/iPhone Simulator/7.0/Applications/5100B004-D9DB-46D5-877F-0CACA7F72699/Documents/video/aaa.mp4";
    [self saveV:vPath];
    
    
    //    NSArray* allLocalFolderInfos = [fileOp searchAllFiles];
    //    [DDConstants removeAllFilesByCode:LOCAL_CODE];
//    sleep(30);
//    NSArray* arr = [[DDConstants shardLocalFolderInfos]objectAtIndex:0];
//    DDImagePickerController *imageC = [[DDImagePickerController alloc]initWithNibName:nil bundle:nil];
//    imageC.fileDataSource = arr;
//    self.window.rootViewController = imageC;
    
    
    
//    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];//生成整个photolibrary句柄的实例
//    NSMutableArray *mediaArray = [[NSMutableArray alloc]init];//存放media的数组
//    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {//获取所有group
//        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {//从group里面
//            NSString* assetType = [result valueForProperty:ALAssetPropertyType];
//            if ([assetType isEqualToString:ALAssetTypePhoto]) {
//                NSLog(@"Photo");
//            }else if([assetType isEqualToString:ALAssetTypeVideo]){
//                NSLog(@"Video");
//            }else if([assetType isEqualToString:ALAssetTypeUnknown]){
//                NSLog(@"Unknow AssetType");
//            }
//            
//            NSDictionary *assetUrls = [result valueForProperty:ALAssetPropertyURLs];
//            NSLog(@"name------%@",[[result valueForProperty:ALAssetPropertyRepresentations]objectAtIndex:0]);
//            NSUInteger assetCounter = 0;
//            for (NSString *assetURLKey in assetUrls) {
//                NSLog(@"Asset URL %lu = %@",(unsigned long)assetCounter,[assetUrls objectForKey:assetURLKey]);
//            }
//            
//            NSLog(@"Representation Size = %lld",[[result defaultRepresentation]size]);
//        }];
//    } failureBlock:^(NSError *error) {
//        NSLog(@"Enumerate the asset groups failed.");
//    }];
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self closeAndDisplayLogin];
    exit(0);
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma close app

-(void)closeAndClead{
    [DDVerifyThread closeAndClead];
    [DDTCPListenThread closeAndClear];
    self.loginViewController = [[[DDLoginViewController alloc] initWithNibName:nil bundle:nil] autorelease];
    self.window.rootViewController = self.loginViewController;
    [self.loginViewController serverClosed];
}

- (void)copyTempVideoToMediaLibrary :(NSString *)videoURL {
    
    dispatch_queue_t mainQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_async(mainQueue, ^{
        
        ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init] autorelease];
        
        ALAssetsLibraryWriteVideoCompletionBlock completionBlock = ^(NSURL *assetURL, NSError *error) {
            NSLog(@"Saved URL: %@", assetURL);
            NSLog(@"Error: %@", error);
            
            if (assetURL != nil) {
                
                AVURLAsset *theAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:videoURL] options:nil];
                
                NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:theAsset];
                
                AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:theAsset presetName:AVAssetExportPresetLowQuality];
                
                [exportSession setOutputURL:[NSURL URLWithString:videoURL]];
                [exportSession setOutputFileType:AVFileTypeQuickTimeMovie];
                
                [exportSession exportAsynchronouslyWithCompletionHandler:^ {
                    switch ([exportSession status]) {
                        case AVAssetExportSessionStatusFailed:
                            NSLog(@"Export session faied with error: %@", [exportSession error]);
                            break;
                        default:
                            //[self mediaIsReady];
                            break;
                    }
                }];
            }
        };
        
        [library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:videoURL] completionBlock:completionBlock];
    });
}

- (void)saveV:(NSString*)urlString{
    NSLog(@"v path---------------%@",urlString);
//    [self copyTempVideoToMediaLibrary:urlString];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    if ( UIVideoAtPathIsCompatibleWithSavedPhotosAlbum( urlString )) {
        NSLog(@"-------------save ok");
        //UISaveVideoAtPathToSavedPhotosAlbum(urlString,nil,nil,nil);
    }
    
    [library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:urlString]
                                completionBlock:^(NSURL *assetURL, NSError *error) {
                                    if (error) {
                                        NSLog(@"Save video fail:%@",error);
                                    } else {
                                        NSLog(@"Save video succeed.%@",assetURL);
                                    }
                                }];
}


@end
